package models

import (
	"strconv"
	"strings"
	"time"

	"github.com/astaxie/beego"
	"github.com/astaxie/beego/orm"
	"github.com/chanxuehong/wechat.v2/mp/message/callback/response"
)

type Article struct {
	Id         int
	Title      string
	Content    string `orm:"type(text)"`
	Type       string
	Desc       string `orm:"type(text)"`
	MapImg     string `orm:"type(text)"`
	MapWxImg   string `orm:type(text)`
	PicUrl     string `orm:type(text)`
	Url        string `orm:type(text)`
	Order      string
	IsValid    string
	EventKey   string
	IsNews     string
	IsMenuNews string
	MediaId    string
	TaskId     string
	IsUpdate   string
	ThumbPath  string
	CompanyId  string
	CreatedAt  time.Time `orm:"auto_now_add;type(datetime)"`
	UpdateAt   time.Time `orm:"auto_now;type(datetime)"`
}

func GetArticleByEventKey(eventKey string, cid int64) (*[]response.Article, error) {
	o := orm.NewOrm()
	var maps []orm.Params
	articles := []response.Article{}
	_, err := o.QueryTable("article").Filter("CompanyId", cid).Filter("EventKey__exact", eventKey).Filter("IsValid__exact", "1").Filter("IsMenuNews__exact", "1").OrderBy("Order", "-Id").Limit(10).Values(&maps, "Title", "Desc", "PicUrl", "Url")
	if err != nil {
		return &articles, err
	}
	for _, m := range maps {
		article := response.Article{m["Title"].(string), m["Desc"].(string), m["PicUrl"].(string), m["Url"].(string)}
		articles = append(articles, article)
	}
	return &articles, nil

}
func GetArticleByNewsIds(newsIds string, cid int64) (*[]response.Article, error) {
	newsIds = strings.TrimSpace(newsIds)
	newsIds = strings.Trim(newsIds, ",")
	newsIdSlice := strings.Split(newsIds, ",")
	var ids []int
	articles := []response.Article{}
	for _, id := range newsIdSlice {
		n, err := strconv.Atoi(id)
		if err != nil {
			beego.Error("GetArticleByNewsIds news ids convert to int err ", err.Error())
			return &articles, err
		}
		ids = append(ids, n)
	}
	o := orm.NewOrm()
	var maps []orm.Params

	_, err := o.QueryTable("article").Filter("CompanyId", cid).Filter("Id__in", ids).Filter("IsValid__exact", "1").OrderBy("Order", "-Id").Limit(10).Values(&maps, "Title", "Desc", "PicUrl", "Url")
	if err != nil {
		beego.Error("GetArticleByNewsIds error ", err.Error())
		return &articles, err
	}
	for _, m := range maps {
		article := response.Article{m["Title"].(string), m["Desc"].(string), m["PicUrl"].(string), m["Url"].(string)}
		articles = append(articles, article)
	}
	return &articles, nil

}
